package services

import (
	"925/video-srv/basic/config"
	__ "925/video-srv/basic/proto"
	"925/video-srv/model"
	"925/video-srv/pkg"
	"context"
	"fmt"
)

type Server struct {
	__.UnsafeVideoServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) VideoAdd(_ context.Context, in *__.VideoAddReq) (*__.VideoAddResp, error) {
	var video = model.Video{
		Title:       in.Title,
		CovUrl:      in.CovUrl,
		CheckStatus: "待审核",
		PlayCount:   0,
	}
	config.DB.Debug().Create(&video)
	return &__.VideoAddResp{
		VideoId: int64(video.ID),
	}, nil
}

func (s *Server) VideoEpAdd(_ context.Context, in *__.VideoEpAddReq) (*__.VideoEpAddResp, error) {
	var videoEp = model.VideoEp{
		VideoId: int(in.VideoId),
		Title:   in.Title,
		Types:   in.Types,
		Desc:    in.Desc,
	}
	begin := config.DB.Begin()
	if err := begin.Create(&videoEp).Error; err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("添加失败")
	}
	begin.Commit()
	return &__.VideoEpAddResp{VideoEpId: int64(videoEp.ID)}, nil
}
func (s *Server) VideoCheck(_ context.Context, in *__.VideoCheckReq) (*__.VideoCheckResp, error) {
	var video model.Video
	if err := config.DB.Debug().Where("id = ?", in.VideoId).Find(&video).Error; err != nil {
		return nil, fmt.Errorf("查找失败")
	}
	if video.ID == 0 {
		return nil, fmt.Errorf("没有这个视频")
	}
	var status string
	if pkg.Baidu(video.Title) {
		status = "驳回"
		config.DB.Model(&model.Video{}).Where("id = ?", in.VideoId).Update("check_status", status)
	} else {
		status = "通过"
		config.DB.Model(&model.Video{}).Where("id = ?", in.VideoId).Update("check_status", status)
	}

	var videocheck = model.Check{
		UserId:       int(in.UserId),
		VideoId:      int(in.VideoId),
		CheckStatus:  status,
		CheckMessage: in.CheckMessage,
	}
	config.DB.Debug().Create(&videocheck)
	return &__.VideoCheckResp{CheckId: int64(videocheck.ID)}, nil
}
func (s *Server) Vip(_ context.Context, in *__.VipReq) (*__.VipResp, error) {

	if in.UserId == 0 {
		return nil, fmt.Errorf("用户未登录")
	}
	if in.IsVip != 2 {
		return nil, fmt.Errorf("用户不是会员")
	}
	var video model.Video
	if err := config.DB.Debug().Where("id = ?", in.VideoId).Find(&video).Error; err != nil {
		return nil, fmt.Errorf("查找失败")
	}
	return &__.VipResp{
		VideoId: int64(video.ID),
		Message: "查看成功",
	}, nil
}
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {

	var user model.User
	config.DB.Debug().Where("name = ?", in.Name).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("未找到用户")
	}

	return &__.LoginResp{
		UserId: int64(user.ID),
		IsVip:  int64(user.IsVip),
	}, nil
}
func (s *Server) IsVip(_ context.Context, in *__.IsVipReq) (*__.IsVipResp, error) {
	var user model.User
	config.DB.Debug().Where("name = ?", in.Name).Find(&user)
	if user.IsVip == 1 {
		return nil, fmt.Errorf("该用户不是会员")
	}
	return &__.IsVipResp{
		UserId: int64(user.ID),
		IsVip:  int64(user.IsVip),
	}, nil
}
